package com.apes.fn.business.insurance.modle;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName CommissionReconciliation
 * @Author wsj
 * @Date 2021/6/16 15:59
 * @description 佣金对账单
 */

@Entity
@EntityListeners(DefaultPersistListener.class)
@Getter
@Setter
@Table(name = CommissionReconciliation.CONST_TABLE_NAME)
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
public class CommissionReconciliation extends Model {
    public final static String CONST_TABLE_NAME = "commission_reconciliation";

    @Id
    @Column(name = "id", nullable = false, length = 20)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "佣金对帐单", padding = 5, prefix = "YJ%(company)%(yy)%(month)", useDateRange = true)
    @Comment("佣金对帐单号")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier", referencedColumnName = "id", nullable = false)
    @Comment("供应商")
    private PartyRole supplier;

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "start_Date")
    @Comment("开始时间")
    private Date startDate;

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "end_Date")
    @Comment("结束时间")
    private Date endDate;

    @Column(name = "retail_Order", length = 4000)
    @Comment("销售订单号")
    private String retailOrder;

    public JSONArray getRetailOrderList() {
        if (retailOrder!=null){
            JSONArray jsonArray = JSONArray.parseArray(retailOrder);
            JSONArray id = jsonArray.stream().filter(o -> o instanceof String).map(o -> MapUtil.mapper("id", o)).collect(Collectors.toCollection(JSONArray::new));
            //为了旧数据做兼容
            if (id.isEmpty())return jsonArray;
            return id;
        }
        return retailOrderList;
    }

    public void setRetailOrderList(JSONArray retailOrderList) {
        if (retailOrderList==null||retailOrderList.isEmpty())return;
        List<String> idList = retailOrderList.stream().map(o -> {
            JSONObject jsonObject = (JSONObject) o;
            return jsonObject.getString("id");
        }).collect(Collectors.toList());
        this.retailOrder = JSONArray.toJSONString(idList) ;
    }

    @Transient
    private JSONArray retailOrderList;


    @Column(name = "contract", length = 64)
    @Comment("合同号")
    private String contract;

    @Column(name = "cooperation_Type", length = 64)
    @Comment("合作方式")
    private String cooperationType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司")
    private PartyRole company;


    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "invoice_Date")
    @Comment("申请发票时间")
    private Date invoiceDate;

    @Comment("发票金额")
    @Column(name = "invoice_Amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double invoiceAmount = 0;

    @Comment("使用发票金额")
    @Column(name = "use_Invoice_Quota", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double useInvoiceQuota = 0;

    @Comment("佣金金额")
    @Column(name = "commission", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double commission = 0;

    @Comment("保险公司佣金")
    @Column(name = "insurance_Commission", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double insuranceCommission = 0;

    @Comment("调整金额")
    @Column(name = "adjustment_Amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double adjustmentAmount = 0;

    @Comment("差价合计")
    @Column(name = "difference_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double differencePrice = 0;

    @Comment("佣金类型")
    @Column(name = "commission_type")
    private String commissionType ;

    @Comment("险种")
    @Column(name = "insurance_type")
    private String insuranceType ;

    @Column(name = "invoice", nullable = false, columnDefinition = "number(1, 0) default 0")
    @Comment("是否开票")
    private boolean invoice;

    @Column(name = "remark")
    @Comment("备注")
    private String remark;

    @States(name = "单据状态", values = {
            @State(id = "create", name = "新增"),
            @State(id = "delete", name = "删除"),
            @State(id = "approve", name = "审核"),
            @State(id = "portion", name = "部分到账"),
            @State(id = "all", name = "全部到账")
    })
    @Column(name = "state", length = 32, nullable = false)
    @Comment("单据状态")
    private String state = "create";

    @Column(name = "creator_Name")
    @Comment("制单人")
    private String creatorName;


    @Column(name = "approve_People")
    @Comment("审核人")
    private String approvePeople;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "approve_Date")
    @Comment("审核时间")
    private Date approveDate;




    @OneToMany(mappedBy = "commissionReconciliation", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CommissionReconciliationItem> reconciliationItems = new ArrayList<>();

    public List<CommissionReconciliationItem> getReconciliationItems() {
        for (CommissionReconciliationItem item : reconciliationItems) {
            item.setCommissionReconciliation(this);
        }
        return reconciliationItems;
    }


    @OneToMany(mappedBy = "commissionReconciliation", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<InAccountInformation> inAccountInformations = new ArrayList<>();
    public List<InAccountInformation> getInAccountInformations() {
        if (Objects.isNull(inAccountInformations)) {
            return new ArrayList<>();
        }
        for (InAccountInformation item : inAccountInformations) {
            item.setCommissionReconciliation(this);
        }
        return inAccountInformations;
    }



    @OneToMany(mappedBy = "commissionReconciliation", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<InsuranceCommissionItem> insuranceCommissionItems = new ArrayList<>();

    public List<InsuranceCommissionItem> getInsuranceCommissionItems() {
        if (Objects.isNull(insuranceCommissionItems)) {
            return new ArrayList<>();
        }
        for (InsuranceCommissionItem item : insuranceCommissionItems) {
            item.setCommissionReconciliation(this);
        }
        return insuranceCommissionItems;
    }
}
